import { DrawerForm, ProList } from '@ant-design/pro-components';
import { Button, Popover, Space, Tag } from 'antd';
import { ItemType } from 'antd/es/menu/hooks/useItems';
import React, { useEffect, useState } from 'react';
import PreviewDrawerEdit from './PreviewDrawerEdit';
import PreviewDrawerHTML from './PreviewDrawerHTML';

interface PreviewDrawerProps {
  menuItems: ItemType[];
  statistics: string;
  selectedRows: NewsData.PageResult[];
}

const PreviewDrawer: React.FC<PreviewDrawerProps> = ({ menuItems, statistics, selectedRows }) => {
  const [menuDataSource, setMenuSourceState] = useState<PreviewDrawerBean.PreviewBean[]>([]);

  /**
   * 强制刷新
   */
  const [, updateState] = React.useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);

  const rendering = () => {
    let datas: PreviewDrawerBean.PreviewBean[] = [];

    menuItems.forEach((element) => {
      const list = selectedRows.filter((item) => item.menuKey === element?.key);

      if (list.length > 0) {
        let bean: PreviewDrawerBean.PreviewBean = {
          menuLabel: element?.label,
          menuKey: element?.key,
          selecteds: list,
        };

        datas.push(bean);
      }
    });

    setMenuSourceState(datas);
    return datas;
  };

  useEffect(() => {
    rendering();
  }, [selectedRows]);

  return (
    <DrawerForm
      title="预览"
      trigger={
        <Button key="preview" type="primary">
          预览（{statistics}）
        </Button>
      }
      drawerProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <PreviewDrawerHTML key="PreviewDrawerHTML" dataSource={menuDataSource} />,
          ];
        },
      }}
      onFinish={async (values) => {
        return false;
      }}
      onOpenChange={(visible) => {
        if (!visible) {
          setMenuSourceState(rendering());
        }
      }}
    >
      {menuDataSource.map((item) => (
        <ProList
          key={item.menuKey + item.menuLabel}
          rowKey="id"
          headerTitle={item.menuLabel}
          dataSource={item.selecteds}
          showActions="always"
          metas={{
            title: {
              dataIndex: 'title',
              render: (dom: React.ReactNode, entity) => {
                return (
                  <Popover
                    overlayInnerStyle={{
                      width: '450px',
                    }}
                    content={
                      entity.generalization == undefined ? entity.summaries : entity.generalization
                    }
                    title="摘要"
                    trigger="hover"
                  >
                    <a
                      href={entity.sourceUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      key={`view-${entity.id}`}
                    >
                      {entity.title}
                    </a>
                  </Popover>
                );
              },
            },
            description: {
              dataIndex: 'summaries',
              render: (dom: React.ReactNode, entity) => {
                return (
                  <div>
                    {entity.generalization == undefined ? entity.summaries : entity.generalization}
                  </div>
                );
              },
            },
            subTitle: {
              dataIndex: 'site',
              render: (dom: React.ReactNode, entity) => {
                return (
                  <Space size={0}>
                    <Tag color="blue">{entity?.site}</Tag>
                    <Tag color="green">{entity?.province}</Tag>
                  </Space>
                );
              },
            },
            actions: {
              render: (text, row, index, action) => [
                <PreviewDrawerEdit
                  key="PreviewDrawerEdit"
                  data={row}
                  onSave={(title, generalization) => {
                    menuDataSource.forEach((data) => {
                      if (data.menuKey === item.menuKey) {
                        data.selecteds.forEach((item) => {
                          if (item.id === row.id) {
                            item.title = title;
                            item.generalization = generalization;
                          }
                        });
                      }
                    });
                    setMenuSourceState(menuDataSource);
                    forceUpdate();
                  }}
                />,
                <a
                  key={row.uuid + row.id + index}
                  onClick={() => {
                    let newList = new Array();

                    menuDataSource.forEach((item) => {
                      const selecteds = item.selecteds.filter((entity) => entity.id !== row.id);

                      if (selecteds.length > 0) {
                        let newData: PreviewDrawerBean.PreviewBean = {
                          menuLabel: item.menuLabel,
                          menuKey: item.menuKey,
                          selecteds: selecteds,
                        };
                        newList.push(newData);
                      }
                    });
                    setMenuSourceState(newList);
                    forceUpdate();
                  }}
                >
                  删除
                </a>,
              ],
            },
          }}
        />
      ))}
    </DrawerForm>
  );
};

export default PreviewDrawer;
